package cn.kgc.listener;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.sql.DataSource;
import java.sql.Connection;

public class DatabaseListener implements ServletContextListener {


    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        String JNDINAME = "java:comp/env/jdbc/news" ;
        Connection conn = null ;
        ServletContext sc=servletContextEvent.getServletContext();
        try
        {
            // 初始化查找命名空间
            Context ctx = new InitialContext() ;
            // 找到DataSource
            DataSource ds = (DataSource)ctx.lookup(JNDINAME) ;
            sc.setAttribute("datasource",ds);
        }
        catch(Exception e)
        {
            System.out.println(e) ;
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
